/**
 * AI内存管理Hook
 * 提供对话历史、文档记忆、学习记录等功能
 */

import { useState, useCallback, useEffect } from 'react'

// 内存条目类型
export interface MemoryEntry {
  id: string
  type: 'conversation' | 'document' | 'context' | 'user_preference'
  content: string
  metadata: Record<string, any>
  timestamp: Date
  importance: number
  tags: string[]
}

// 搜索结果
export interface MemorySearchResult {
  entry: MemoryEntry
  relevanceScore: number
  matchType: 'exact' | 'partial' | 'semantic'
}

// AI内存状态
export interface AIMemoryState {
  isLoading: boolean
  memories: MemoryEntry[]
  searchResults: MemorySearchResult[]
  error: string | null
  stats: any
}

export const useAIMemory = () => {
  const [state, setState] = useState<AIMemoryState>({
    isLoading: false,
    memories: [],
    searchResults: [],
    error: null,
    stats: null,
  })

  // 加载记忆数据
  const loadMemories = useCallback(async (type?: string, limit?: number) => {
    setState(prev => ({
      ...prev,
      isLoading: true,
      error: null,
    }))

    try {
      // 通过IPC调用主进程的内存服务
      let memories: MemoryEntry[] = []
      if (window.electronAPI.memory.retrieve) {
        const result = await window.electronAPI.memory.retrieve(type, undefined, { limit })
        memories = Array.isArray(result) ? result : [result].filter(Boolean)
      }

      setState(prev => ({
        ...prev,
        isLoading: false,
        memories,
      }))
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to load memories'
      setState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
      }))
    }
  }, [])

  // 存储记忆
  const storeMemory = useCallback(async (
    type: 'conversation' | 'document' | 'context' | 'user_preference',
    content: string,
    metadata: Record<string, any> = {},
    options: { importance?: number; tags?: string[] } = {}
  ): Promise<MemoryEntry | null> => {
    try {
      const memoryData = {
        type,
        content,
        metadata,
        importance: options.importance || 0.5,
        tags: options.tags || [],
      }

      let result: MemoryEntry | null = null
      if (window.electronAPI.memory.store) {
        result = await window.electronAPI.memory.store(memoryData)
      }

      if (result) {
        setState(prev => ({
          ...prev,
          memories: [result, ...prev.memories].slice(0, 100), // 限制数量
        }))
      }

      return result
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to store memory'
      setState(prev => ({
        ...prev,
        error: errorMessage,
      }))
      return null
    }
  }, [])

  // 搜索记忆
  const searchMemories = useCallback(async (
    query: string,
    type?: string,
    limit: number = 10
  ): Promise<MemorySearchResult[]> => {
    setState(prev => ({
      ...prev,
      isLoading: true,
      error: null,
    }))

    try {
      let results: MemorySearchResult[] = []
      if (window.electronAPI.memory.search) {
        const memoryResults = await window.electronAPI.memory.search(query, type, { limit })
        results = Array.isArray(memoryResults) ? memoryResults : []
      }

      setState(prev => ({
        ...prev,
        isLoading: false,
        searchResults: results,
      }))

      return results
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Search failed'
      setState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
        searchResults: [],
      }))
      return []
    }
  }, [])

  // 删除记忆
  const deleteMemory = useCallback(async (id: string): Promise<boolean> => {
    try {
      let success = false
      if (window.electronAPI.memory.delete) {
        success = await window.electronAPI.memory.delete(id)
      }

      if (success) {
        setState(prev => ({
          ...prev,
          memories: prev.memories.filter(m => m.id !== id),
          searchResults: prev.searchResults.filter(r => r.entry.id !== id),
        }))
      }

      return success
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to delete memory'
      setState(prev => ({
        ...prev,
        error: errorMessage,
      }))
      return false
    }
  }, [])

  // 更新记忆
  const updateMemory = useCallback(async (
    id: string,
    updates: Partial<MemoryEntry>
  ): Promise<MemoryEntry | null> => {
    try {
      let result: MemoryEntry | null = null
      if (window.electronAPI.memory.update) {
        result = await window.electronAPI.memory.update(id, updates)
      }

      if (result) {
        setState(prev => ({
          ...prev,
          memories: prev.memories.map(m => m.id === id ? result : m),
        }))
      }

      return result
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to update memory'
      setState(prev => ({
        ...prev,
        error: errorMessage,
      }))
      return null
    }
  }, [])

  // 清空记忆
  const clearMemories = useCallback(async (type?: string): Promise<boolean> => {
    try {
      let success = false
      if (window.electronAPI.memory.clear) {
        success = await window.electronAPI.memory.clear(type)
      }

      if (success) {
        setState(prev => ({
          ...prev,
          memories: type ? prev.memories.filter(m => m.type !== type) : [],
          searchResults: [],
        }))
      }

      return success
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to clear memories'
      setState(prev => ({
        ...prev,
        error: errorMessage,
      }))
      return false
    }
  }, [])

  // 获取统计信息
  const getStats = useCallback(async (): Promise<any> => {
    try {
      let stats = null
      if (window.electronAPI.memory.getStats) {
        stats = await window.electronAPI.memory.getStats()
      }

      setState(prev => ({
        ...prev,
        stats,
      }))

      return stats
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Failed to get stats'
      setState(prev => ({
        ...prev,
        error: errorMessage,
      }))
      return null
    }
  }, [])

  // 便捷方法：存储对话
  const storeConversation = useCallback(async (
    content: string,
    metadata: Record<string, any> = {}
  ): Promise<MemoryEntry | null> => {
    return storeMemory('conversation', content, metadata, {
      importance: 0.6,
      tags: ['conversation'],
    })
  }, [storeMemory])

  // 便捷方法：存储文档
  const storeDocument = useCallback(async (
    content: string,
    metadata: Record<string, any> = {}
  ): Promise<MemoryEntry | null> => {
    return storeMemory('document', content, metadata, {
      importance: 0.8,
      tags: ['document'],
    })
  }, [storeMemory])

  // 便捷方法：存储上下文
  const storeContext = useCallback(async (
    content: string,
    metadata: Record<string, any> = {}
  ): Promise<MemoryEntry | null> => {
    return storeMemory('context', content, metadata, {
      importance: 0.7,
      tags: ['context'],
    })
  }, [storeMemory])

  // 便捷方法：存储用户偏好
  const storeUserPreference = useCallback(async (
    preference: string,
    value: any,
    metadata: Record<string, any> = {}
  ): Promise<MemoryEntry | null> => {
    const content = `${preference}: ${JSON.stringify(value)}`
    return storeMemory('user_preference', content, {
      preference,
      value,
      ...metadata,
    }, {
      importance: 0.9,
      tags: ['preference', preference],
    })
  }, [storeMemory])

  // 搜索相关记忆
  const searchRelatedMemories = useCallback(async (
    content: string,
    limit: number = 5
  ): Promise<MemorySearchResult[]> => {
    // 提取关键词进行搜索
    const keywords = content.split(/\s+/).slice(0, 5).join(' ')
    return searchMemories(keywords, undefined, limit)
  }, [searchMemories])

  // 获取最近的记忆
  const getRecentMemories = useCallback((type?: string, limit: number = 10): MemoryEntry[] => {
    let filtered = state.memories
    if (type) {
      filtered = filtered.filter(m => m.type === type)
    }
    return filtered
      .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
      .slice(0, limit)
  }, [state.memories])

  // 清除搜索结果
  const clearSearchResults = useCallback(() => {
    setState(prev => ({
      ...prev,
      searchResults: [],
    }))
  }, [])

  // 初始化时加载记忆
  useEffect(() => {
    loadMemories()
    getStats()
  }, [loadMemories, getStats])

  return {
    // 状态
    ...state,

    // 方法
    loadMemories,
    storeMemory,
    searchMemories,
    deleteMemory,
    updateMemory,
    clearMemories,
    getStats,

    // 便捷方法
    storeConversation,
    storeDocument,
    storeContext,
    storeUserPreference,
    searchRelatedMemories,
    getRecentMemories,
    clearSearchResults,
  }
}